package com.ailanyin.soft.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 操作数据库
 *
 * @author ailanyin
 * @version 1.0
 * @since 2022-1-7 11:12:01
 */
public class DbUtil {

    private static Statement stmt = null;
    private static Connection connection = null;

    public static void runSql(String sql, String password) {
        try {
            //1.加载jdbc驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取远程mysql连接
            String url = "jdbc:mysql://127.0.0.1:3306/mysql?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
            String user = "root";
            connection = DriverManager.getConnection(url, user, password);
            //3.开启sql称述，（Statement，PreparedStatement（？占位符形式）），执行sql语句
            stmt = connection.createStatement();
            stmt.executeUpdate(sql);
            //4.获取结果集（只有查询有）
            //5.对结果集进行操作（只有查询有）
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

}
